package com.jmu.edu.IMApplication.fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.Environment;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.android.flexbox.FlexboxLayout;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.imageview.ShapeableImageView;
import com.jmu.edu.IMApplication.MainActivity;
import com.jmu.edu.IMApplication.MyApplication;
import com.jmu.edu.IMApplication.R;
import com.jmu.edu.IMApplication.event.RefreshEvent;
import com.jmu.edu.IMApplication.utils.ImageTools;
import com.jmu.edu.IMApplication.utils.LoginUtils;
import com.jmu.edu.IMApplication.utils.ViewUtils;
import com.jmu.edu.IMApplication.utils.WillowUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.GetAvatarBitmapCallback;
import cn.jpush.im.api.BasicCallback;

import static android.content.Context.MODE_PRIVATE;


public class MyFragment extends Fragment {
    private ShapeableImageView backgroundImage, avatarImage;
    private MaterialButton signatureButton, tagButton, nameButton, logoutButton, settingButton;
    private GestureDetector gestureDetector;


    public MyFragment() {
        // Required empty public constructor
    }

    @Override
    public void onResume() {
        super.onResume();
        initViewListener();

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        //show的时候需要重新注册跟view相关的监听
        if (hidden) {
            //Toast.makeText(getContext(), "hidden", Toast.LENGTH_SHORT).show();
        } else {
            initViewListener();
            fillViewWithValues();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_my, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView() {
        backgroundImage = getView().findViewById(R.id.fragment_my_background);
        avatarImage = getView().findViewById(R.id.fragment_my_avatar);
        nameButton = getView().findViewById(R.id.fragment_my_name);
        signatureButton = getView().findViewById(R.id.fragment_my_signature);
        logoutButton = getView().findViewById(R.id.fragment_my_logout);
        tagButton = getView().findViewById(R.id.fragment_my_tag);
        settingButton = getView().findViewById(R.id.fragment_my_setting);
        initListener();
        loadData();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //如果没有data，意味着跳转过去后没有进行有效操作就重新回到app了，这个时候不应该有额外的操作
        if (data == null) {
            return;
        }
        // 1代表是点击头像跳转到相册
        if (requestCode == 1) {
            //获取图片文件
            String filePath = ImageTools.getFilePathFromURI(getActivity(), data.getData());
            Glide.with(avatarImage).load(filePath).into(avatarImage);
            File file = new File(filePath);
            WillowUtils.updateUserAvatar(file, new BasicCallback() {
                @Override
                public void gotResult(int i, String s) {
                    //如果上传头像成功，则删除该文件
                    if (i == 0) {
                        Toast.makeText(getContext(), "更新头像成功", Toast.LENGTH_SHORT).show();
                        //删除该文件 返回值为boolean
                        file.delete();
                        MyApplication.setUser(WillowUtils.getMyInfo());
                        EventBus.getDefault().post(new RefreshEvent("main"));
                    } else {
                        Toast.makeText(getContext(), "更新头像失败，请检查网络连接或权限设置", Toast.LENGTH_SHORT).show();
                    }
                }
            });


        }


    }

    private void initViewListener() {
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        //左滑右滑监听必须要设置允许长按
        getView().setLongClickable(true);
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
                    ViewUtils.hideFragment(MyFragment.this, R.anim.from_left, R.anim.out_left);
                    return true;
                }
                return false;
            }
        });
        getView().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return gestureDetector.onTouchEvent(event);
            }
        });
    }

    private void initListener() {
        gestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                float xToLeft = e1.getX() - e2.getX();
                float xToRight = e2.getX() - e1.getX();
                //如果向左移动的距离大于最小移动距离且移动速度大于最小移动速度，那么满足左滑手势的条件,反之满足向右滑动
                if (xToLeft > ViewUtils.MIN_FLING_DISTANCE && Math.abs(velocityX) > ViewUtils.MIN_FLING_VELOCITY) {
                    ViewUtils.hideFragment(MyFragment.this, R.anim.from_left, R.anim.out_left);
                    return true;
                } else if (xToRight > ViewUtils.MIN_FLING_DISTANCE && Math.abs(velocityX) > ViewUtils.MIN_FLING_VELOCITY) {
                    return false;
                }
                return false;
            }
        });


        //background和avatar的点击事件相同，都是点击后弹出popupMenu，然后跳转到相册界面选择图片
        backgroundImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        avatarImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intent, 1);
            }
        });

        //跳转到个性签名修改界面
        signatureButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("type", "signature");
                Fragment show = MyApplication.fragmentManager.findFragmentByTag("nameAndSignature");
                if (show == null) {
                    show = new NameAndSignatureFragment();
                }
                show.setArguments(bundle);
                ViewUtils.hideFragment(MyFragment.this, show, "nameAndSignature", R.anim.from_right, R.anim.out_left);
            }
        });
        //跳转到昵称修改界面
        nameButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("type", "name");
                Fragment show = MyApplication.fragmentManager.findFragmentByTag("nameAndSignature");
                if (show == null) {
                    show = new NameAndSignatureFragment();
                }
                show.setArguments(bundle);
                ViewUtils.hideFragment(MyFragment.this, show, "nameAndSignature", R.anim.from_right, R.anim.out_left);
            }
        });
        //跳转到标签具体展示界面
        tagButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String tag = "showTag";
                ShowTagFragment show = (ShowTagFragment) MyApplication.fragmentManager.findFragmentByTag(tag);
                if (show == null) {
                    show = new ShowTagFragment();
                }
                show.setUserInfo(MyApplication.getUser());
                Bundle bundle = new Bundle();
                bundle.putString("backTag", "my");
                show.setArguments(bundle);
                ViewUtils.hideFragment(MyFragment.this, show, tag, R.anim.from_right, R.anim.out_left);
            }
        });
        settingButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        //退出登录，重启activity
        logoutButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LoginUtils.logout();
                MainActivity mainActivity = (MainActivity) getActivity();
                mainActivity.reStartActivity();

            }
        });
    }

    private void loadData() {
        fillViewWithValues();

    }

    private void fillViewWithValues() {
        nameButton.setText(WillowUtils.getMyNickName());

        signatureButton.setText(WillowUtils.getSignature(MyApplication.getUser()));

        WillowUtils.getMyInfo().getAvatarBitmap(new GetAvatarBitmapCallback() {
            @Override
            public void gotResult(int i, String s, Bitmap bitmap) {
                if (bitmap != null) {
                    Glide.with(avatarImage).load(bitmap).into(avatarImage);
                }
            }
        });
    }

}